package com.usian.search.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.model.behavior.pojos.ApBehaviorEntry;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.search.pojos.ApUserSearch;
import com.usian.model.user.dtos.UserSearchDto;
import com.usian.model.user.pojos.ApUser;
import com.usian.search.feign.BehaviorFeign;
import com.usian.search.mapper.ApUserSearchMapper;
import com.usian.search.service.ApUserSearchService;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApUserSearchServiceImpl  extends ServiceImpl<ApUserSearchMapper, ApUserSearch> implements ApUserSearchService {

    @Autowired
    private BehaviorFeign behaviorFeign;

    @Override
    public ResponseResult findUserSearch(UserSearchDto userSearchDto) {

        //分页参数大于50不做查询
        if(userSearchDto.getPageSize() > 50){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //entryId 远程
        ApUser user = AppThreadLocalUtils.getUser();
        ApBehaviorEntry apBehaviorEntry = behaviorFeign.findByUserIdOrEntryId(user.getId(), userSearchDto.getEquipmentId());
        if(apBehaviorEntry ==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        IPage pageParam = new Page(userSearchDto.getPageNum(), userSearchDto.getPageSize());
        IPage page = page(pageParam, Wrappers.<ApUserSearch>lambdaQuery().eq(ApUserSearch::getEntryId, apBehaviorEntry.getId())
                .eq(ApUserSearch::getStatus, 1));


        return ResponseResult.okResult(page.getRecords());
    }

    @Override
    @Async("taskExecutor")
    public void insert(Integer entryId, String searchWords) {

        ApUserSearch apUserSearch = this.getOne(Wrappers.<ApUserSearch>lambdaQuery().eq(ApUserSearch::getEntryId, entryId)
                .eq(ApUserSearch::getKeyword, searchWords));

        //修改
        if(apUserSearch!=null && apUserSearch.getStatus()==1){
            //存在切状态有效不修改
            return;
        }else if(apUserSearch!=null&& apUserSearch.getStatus()==0){
            //无效改成有效
            apUserSearch.setStatus(1);
            this.updateById(apUserSearch);
            return;
        }

        //新增
        apUserSearch = new ApUserSearch();
        apUserSearch.setEntryId(entryId);
        apUserSearch.setStatus(1);
        apUserSearch.setKeyword(searchWords);
        apUserSearch.setCreatedTime(new Date());
        save(apUserSearch);
    }
}
